package com.letoken.platform.job.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.letoken.platform.pub.constant.LetokenUserConstant;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.pub.util.HttpClientUtil;
import com.letoken.platform.repo.app.dao.AppUserMapper;
import com.letoken.platform.repo.app.dto.UpdateImUserInfoDto;
import com.letoken.platform.repo.app.po.AppUser;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.app.redis.AppUserTokenRedis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author letokenlabs
 * @date 2022/12/10$
 */
@RestController
@RequestMapping("/cache")
@Api(tags = "cache")
@Slf4j
public class CaheController {
    @Autowired
    private AppUserMapper appUserMapper;
    /**
     * 批量替换用户头像域名（只执行一次）
     * @return
     */
    @GetMapping("/user/avatar")
    @ApiOperation(value = "批量替换用户头像域名（只执行一次）", notes = "更新头像缓存")
    public ApiResponse updateAvatar() {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("head_portrait like 'https://d2f3kk9ac2k4dp%'");
        List<AppUser> list = appUserMapper.selectList(queryWrapper);
        int count = 0;
        if (!list.isEmpty()) {
            for (AppUser user : list) {
                if (upateAllAvatar(user.getId().toString())) {
                    count++;
                }
            }
        }

        log.info("updateAvatar result >> total: {}, ok: {}, error: {}", list.size(), count, list.size() - count);
        return ApiResponse.create(count);
    }
    private boolean upateAllAvatar(String userId) {
        try {

            // 获取用户token
            String token = AppUserTokenRedis.me().getValue(userId);
            if (token != null && token != "") {
                // 获取缓存appuser
                AppUser appUser = AppLoginTokenRedis.me().getClassObject(token);
                if (appUser != null) {

                    // 修改app avatar
                    appUser.setHeadPortrait(appUser.getHeadPortrait().replaceAll("https://d2f3kk9ac2k4dp.cloudfront.net", "https://images.letokenchat.cc"));
                    appUser.updateById();

                    // 更新app缓存
                    AppLoginTokenRedis.me().put(token, appUser);

                    //修改im用户头像
                    UpdateImUserInfoDto dto = new UpdateImUserInfoDto();
                    dto.setUserId(LetokenUserConstant.USER_ID_PREFIX + appUser.getId());
                    dto.setPortrait(appUser.getHeadPortrait());
                    return upateImAvatar(token, appUser.getId(), dto);
                }
            }

        } catch (Exception e) {
            log.error("upateAllAvatar error! {} , {}", userId, e.toString());
        }
        return false;
    }

    private boolean upateImAvatar(String token, Integer userId, UpdateImUserInfoDto dto) {
        String json = JSONObject.toJSONString(dto);
        String res;
        try {
            String url = "https://im-app.letokenchat.cc/letoken/update_user_info";
            Map<String, String> header = new HashMap<>();
            header.put("letokenToken", token);
            header.put("letokenUserId", userId.toString());
            res = HttpClientUtil.sendPostJson(url, json, header);
            JSONObject jsonObject = JSONObject.parseObject(res);
            Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                log.info("用户：" + dto.getUserId() + " 头像修改信息成功！");
                return true;
            } else {
                log.error("code = " + code + "  用户：" + dto.getUserId() + " 修改用户信息失败！");
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
        return false;
    }

}